package com.jacky.iot.resources;

import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.Utils;
import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.coap.MediaTypeRegistry;
import org.eclipse.californium.core.coap.Request;
import org.eclipse.californium.core.server.resources.CoapExchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class SeparateResource extends CoapResource {

    private static final Logger log = LoggerFactory.getLogger(SeparateResource.class);

    public SeparateResource(String name) {
        super(name);
        getAttributes().setTitle("Resource which cannot be served immediately and which cannot be acknowledged in a piggy-backed way");
    }

    @Override
    public void handleGET(CoapExchange exchange) {
        // 如果处理业务可能需要一些时间并可能在客户端触发超时的情况下,可以在exchange上调用此方法
        // 意思是向客户发送确认通知，告知交易已到达，并且正在计算并将尽快发送单独的消息。
        exchange.accept();
        log.info("[separate] exchange accepted");
        // 模拟业务处理用时
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {

        }
        Request request = exchange.advanced().getRequest();
        log.info("[separate] req hexString:{}", Utils.toHexString(request.getBytes()));
        String payload = String.format("separate Type: %d (%s)\nCode: %d (%s)\nMid: %d",
                request.getType().value,
                request.getType(),
                request.getCode().value,
                request.getCode(),
                request.getMID());
        exchange.respond(CoAP.ResponseCode.CONTENT, payload, MediaTypeRegistry.TEXT_PLAIN);
    }
}
